import React, { useEffect, useState } from "react";
import {
  Card,
  Tree,
  Spin,
  message,
  Pagination,
  Typography,
  Button,
  Modal,
  Form,
  Input,
  Checkbox,
  Select,
  Alert,
  Space,
} from "antd";
import { useTheme } from "../contexts/ThemeContext";
import {
  getCategoryList,
  getAllCategories,
  addCategory,
  addSubCategory,
  deleteCategory,
  batchDeleteCategory,
  deleteSubCategory,
  batchDeleteSubCategory,
  updateCategory,
  updateSubCategory,
} from "../api/category";

import {
  PlusOutlined,
  DeleteOutlined,
  CloseCircleOutlined,
  EditOutlined,
  ReloadOutlined,
} from "@ant-design/icons";

export default function Category() {
  const { isDarkMode } = useTheme();

  // 批量操作
  const [selectedCategoryIds, setSelectedCategoryIds] = useState([]);
  const [selectedSubIds, setSelectedSubIds] = useState([]);
  const [treeData, setTreeData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ page: 1, size: 10 });
  const [total, setTotal] = useState(0);
  // 新增分类弹窗
  // 全选逻辑
  const handleSelectAllCategory = (checked) => {
    if (checked) {
      const categoryKeys = treeData.map((cat) => cat.key);
      setSelectedCategoryIds(categoryKeys);
    } else {
      setSelectedCategoryIds([]);
    }
  };
  const handleSelectAllSub = (checked) => {
    if (checked) {
      const allSubKeys = treeData.flatMap((cat) =>
        (cat.children || []).map((sub) => sub.key)
      );
      setSelectedSubIds(allSubKeys);
    } else {
      setSelectedSubIds([]);
    }
  };

  // Tree选中处理
  const handleTreeCheck = (checkedKeys) => {
    const categoryIds = [];
    const subIds = [];

    checkedKeys.forEach((key) => {
      if (key.startsWith("cat_")) {
        categoryIds.push(key);
      } else if (key.startsWith("sub_")) {
        subIds.push(key);
      }
    });

    setSelectedCategoryIds(categoryIds);
    setSelectedSubIds(subIds);
  };
  const [addModalOpen, setAddModalOpen] = useState(false);
  const [addForm] = Form.useForm();
  // 新增子分类弹窗
  const [addSubModalOpen, setAddSubModalOpen] = useState(false);
  const [addSubForm] = Form.useForm();
  const [currentCategoryId, setCurrentCategoryId] = useState(null);
  // 编辑分类弹窗
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editForm] = Form.useForm();
  const [editCategory, setEditCategory] = useState(null);
  // 编辑子分类弹窗
  const [editSubModalOpen, setEditSubModalOpen] = useState(false);
  const [editSubForm] = Form.useForm();
  const [editSub, setEditSub] = useState(null);
  // 分类列表（用于父分类选择）
  const [categoryList, setCategoryList] = useState([]);

  // 获取所有分类（用于父分类下拉框）
  const fetchAllCategories = async () => {
    try {
      const res = await getAllCategories();
      if (res.code === 1 && res.data) {
        setCategoryList(res.data.list);
      }
    } catch (e) {
      console.error("获取所有分类失败", e);
    }
  };

  // 刷新数据
  const handleRefresh = async () => {
    try {
      setLoading(true);
      await Promise.all([
        fetchCategories(pagination.page, pagination.size, false),
        fetchAllCategories(),
      ]);
      message.success("数据已刷新");
    } catch (error) {
      message.error("刷新失败");
      console.error("刷新数据失败:", error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories(pagination.page, pagination.size);
    fetchAllCategories(); // 获取所有分类用于下拉框
    // eslint-disable-next-line
  }, [pagination.page, pagination.size]);

  const fetchCategories = async (page, size, showLoading = true) => {
    if (showLoading) setLoading(true);
    try {
      const res = await getCategoryList({ page, size });
      if (res.code === 1 && res.data) {
        setTotal(res.data.total);
        setTreeData(
          res.data.list.map((cat) => ({
            title: (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <Button
                  size="small"
                  type="text"
                  danger
                  icon={<DeleteOutlined />}
                  style={{
                    marginRight: 8,
                    width: 20,
                    height: 20,
                    padding: 0,
                    minWidth: 20,
                    borderRadius: 4,
                    fontSize: 12,
                  }}
                  onMouseEnter={(e) => {
                    e.target.style.transform = "scale(1.1)";
                  }}
                  onMouseLeave={(e) => {
                    e.target.style.transform = "scale(1)";
                  }}
                  onClick={async (e) => {
                    e.stopPropagation();
                    Modal.confirm({
                      title: "确认删除该分类？",
                      onOk: async () => {
                        await deleteCategory(cat.id);
                        message.success("删除成功");
                        fetchCategories(pagination.page, pagination.size);
                      },
                    });
                  }}
                  title="删除分类"
                />
                <Button
                  size="small"
                  type="link"
                  icon={<EditOutlined />}
                  style={{ padding: 0, height: 20, marginRight: 4 }}
                  onClick={(e) => {
                    e.stopPropagation();
                    setEditCategory({ id: cat.id, name: cat.name });
                    editForm.setFieldsValue({ name: cat.name });
                    setEditModalOpen(true);
                  }}
                  title="编辑分类"
                />
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    gap: 8,
                    flex: 1,
                    minWidth: 0,
                  }}>
                  <span
                    style={{
                      whiteSpace: "nowrap",
                      overflow: "hidden",
                      textOverflow: "ellipsis",
                    }}>
                    {cat.name}
                  </span>
                  <Button
                    size="small"
                    type="link"
                    icon={<PlusOutlined />}
                    style={{ padding: 0, height: 20 }}
                    onClick={(e) => {
                      e.stopPropagation();
                      setCurrentCategoryId(cat.id);
                      setAddSubModalOpen(true);
                    }}
                    title="添加子分类"
                  />
                </div>
              </div>
            ),
            key: `cat_${cat.id}`,
            children: (cat.subCategories || []).map((sub) => ({
              title: (
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <Button
                    size="small"
                    type="text"
                    danger
                    icon={<DeleteOutlined />}
                    style={{
                      marginRight: 8,
                      width: 20,
                      height: 20,
                      padding: 0,
                      minWidth: 20,
                      borderRadius: 4,
                      fontSize: 12,
                    }}
                    onMouseEnter={(e) => {
                      e.target.style.transform = "scale(1.1)";
                    }}
                    onMouseLeave={(e) => {
                      e.target.style.transform = "scale(1)";
                    }}
                    onClick={async (e) => {
                      e.stopPropagation();
                      Modal.confirm({
                        title: "确认删除该子分类？",
                        onOk: async () => {
                          await deleteSubCategory(sub.id);
                          message.success("删除成功");
                          fetchCategories(pagination.page, pagination.size);
                        },
                      });
                    }}
                    title="删除子分类"
                  />
                  <Button
                    size="small"
                    type="link"
                    icon={<EditOutlined />}
                    style={{ padding: 0, height: 20, marginRight: 4 }}
                    onClick={(e) => {
                      e.stopPropagation();
                      setEditSub({
                        id: sub.id,
                        name: sub.name,
                        categoryId: cat.id,
                      });
                      editSubForm.setFieldsValue({
                        name: sub.name,
                        categoryId: cat.id,
                      });
                      setEditSubModalOpen(true);
                    }}
                    title="编辑子分类"
                  />
                  <div
                    style={{
                      display: "flex",
                      alignItems: "center",
                      gap: 8,
                      flex: 1,
                      minWidth: 0,
                    }}>
                    <span
                      style={{
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                      }}>
                      {sub.name}
                    </span>
                  </div>
                </div>
              ),
              key: `sub_${sub.id}`,
              isLeaf: true,
            })),
          }))
        );
      } else {
        message.error(res.msg || "获取分类失败");
      }
    } catch (e) {
      message.error("获取分类失败");
    } finally {
      if (showLoading) setLoading(false);
    }
  };

  return (
    <div style={{ maxWidth: 700, margin: "20px auto", padding: "0 16px" }}>
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Typography.Title
          level={2}
          style={{ color: "#1890ff", marginBottom: 8 }}>
          分类管理
        </Typography.Title>
        <Typography.Text type="secondary" style={{ fontSize: 16 }}>
          基于 Spring Boot 服务的树状结构的分类与子分类管理
        </Typography.Text>
      </div>
      <Card
        style={{
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          transition: "all 0.3s ease",
        }}
        title={
          <div
            style={{
              display: "flex",
              alignItems: "center",
              gap: 6,
              flexWrap: "wrap",
            }}>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              size="small"
              onClick={() => setAddModalOpen(true)}>
              新增
            </Button>
            <Button
              icon={<ReloadOutlined />}
              size="small"
              onClick={handleRefresh}
              title="刷新数据">
              刷新
            </Button>
            {treeData.length > 0 && (
              <>
                <Checkbox
                  checked={
                    selectedCategoryIds.length > 0 &&
                    selectedCategoryIds.length === treeData.length
                  }
                  indeterminate={
                    selectedCategoryIds.length > 0 &&
                    selectedCategoryIds.length < treeData.length
                  }
                  onChange={(e) => handleSelectAllCategory(e.target.checked)}>
                  全选分类
                </Checkbox>
                <Checkbox
                  checked={
                    selectedSubIds.length > 0 &&
                    selectedSubIds.length ===
                      treeData.flatMap((cat) => cat.children || []).length
                  }
                  indeterminate={
                    selectedSubIds.length > 0 &&
                    selectedSubIds.length <
                      treeData.flatMap((cat) => cat.children || []).length
                  }
                  onChange={(e) => handleSelectAllSub(e.target.checked)}>
                  全选子分类
                </Checkbox>
              </>
            )}
            {selectedCategoryIds.length > 0 && (
              <Button
                danger
                size="small"
                onClick={async () => {
                  Modal.confirm({
                    title: `确认批量删除${selectedCategoryIds.length}个分类？`,
                    onOk: async () => {
                      const categoryIds = selectedCategoryIds.map((key) =>
                        key.replace("cat_", "")
                      );
                      await batchDeleteCategory(categoryIds.join(","));
                      message.success("批量删除成功");
                      setSelectedCategoryIds([]);
                      fetchCategories(pagination.page, pagination.size);
                    },
                  });
                }}
                icon={<DeleteOutlined />}>
                删除分类({selectedCategoryIds.length})
              </Button>
            )}
            {selectedSubIds.length > 0 && (
              <Button
                danger
                size="small"
                onClick={async () => {
                  Modal.confirm({
                    title: `确认批量删除${selectedSubIds.length}个子分类？`,
                    onOk: async () => {
                      const subIds = selectedSubIds.map((key) =>
                        key.replace("sub_", "")
                      );
                      await batchDeleteSubCategory(subIds.join(","));
                      message.success("批量删除成功");
                      setSelectedSubIds([]);
                      fetchCategories(pagination.page, pagination.size);
                    },
                  });
                }}
                icon={<DeleteOutlined />}>
                删除子分类({selectedSubIds.length})
              </Button>
            )}
          </div>
        }>
        {/* 批量选择提示 */}
        {(selectedCategoryIds.length > 0 || selectedSubIds.length > 0) && (
          <Alert
            message={`已选择 ${selectedCategoryIds.length} 个分类，${selectedSubIds.length} 个子分类`}
            type="info"
            showIcon
            closable
            onClose={() => {
              setSelectedCategoryIds([]);
              setSelectedSubIds([]);
            }}
            style={{ marginBottom: 16 }}
          />
        )}
        <Spin spinning={loading}>
          <Tree
            treeData={treeData}
            defaultExpandAll={false}
            showLine={false}
            checkable={true}
            checkedKeys={[...selectedCategoryIds, ...selectedSubIds]}
            onCheck={handleTreeCheck}
            style={{ minHeight: 300 }}
            expandIcon={({ expanded }) => (
              <span
                style={{
                  display: "inline-block",
                  width: 16,
                  textAlign: "center",
                }}>
                {expanded ? "^" : ">"}
              </span>
            )}
          />
          <div style={{ height: 24 }} />
        </Spin>
        <div style={{ marginTop: 24, textAlign: "center" }}>
          <Pagination
            current={pagination.page}
            pageSize={pagination.size}
            total={total}
            showSizeChanger
            pageSizeOptions={["3", "5", "10", "20", "50"]}
            onChange={(p, s) =>
              setPagination((prev) => ({ ...prev, page: p, size: s }))
            }
            showTotal={(t) => `共 ${t} 条`}
          />
        </div>
      </Card>
      {/* 新增分类弹窗 */}
      <Modal
        title="新增分类"
        open={addModalOpen}
        onCancel={() => {
          setAddModalOpen(false);
          addForm.resetFields();
        }}
        onOk={() => addForm.submit()}
        okText="确定"
        cancelText="取消">
        <Form
          form={addForm}
          layout="vertical"
          onFinish={async (values) => {
            try {
              await addCategory({ name: values.name });
              message.success("分类添加成功");
              setAddModalOpen(false);
              addForm.resetFields();
              fetchCategories(pagination.page, pagination.size);
              fetchAllCategories(); // 刷新所有分类列表
            } catch {
              message.error("添加失败");
            }
          }}>
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: "请输入分类名称" }]}>
            <Input placeholder="请输入分类名称" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 新增子分类弹窗 */}
      <Modal
        title="新增子分类"
        open={addSubModalOpen}
        onCancel={() => {
          setAddSubModalOpen(false);
          addSubForm.resetFields();
        }}
        onOk={() => addSubForm.submit()}
        okText="确定"
        cancelText="取消">
        <Form
          form={addSubForm}
          layout="vertical"
          onFinish={async (values) => {
            try {
              await addSubCategory({
                name: values.subName,
                categoryId: currentCategoryId,
              });
              message.success("子分类添加成功");
              setAddSubModalOpen(false);
              addSubForm.resetFields();
              fetchCategories(pagination.page, pagination.size);
            } catch {
              message.error("添加失败");
            }
          }}>
          <Form.Item
            name="subName"
            label="子分类名称"
            rules={[{ required: true, message: "请输入子分类名称" }]}>
            <Input placeholder="请输入子分类名称" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 编辑分类弹窗 */}
      <Modal
        title="编辑分类"
        open={editModalOpen}
        onCancel={() => {
          setEditModalOpen(false);
          editForm.resetFields();
        }}
        onOk={() => editForm.submit()}
        okText="确定"
        cancelText="取消">
        <Form
          form={editForm}
          layout="vertical"
          onFinish={async (values) => {
            try {
              await updateCategory({
                id: editCategory.id,
                name: values.name,
              });
              message.success("分类修改成功");
              setEditModalOpen(false);
              editForm.resetFields();
              fetchCategories(pagination.page, pagination.size);
              fetchAllCategories(); // 刷新所有分类列表
            } catch {
              message.error("修改失败");
            }
          }}>
          <Form.Item
            name="name"
            label="分类名称"
            rules={[{ required: true, message: "请输入分类名称" }]}>
            <Input placeholder="请输入分类名称" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 编辑子分类弹窗 */}
      <Modal
        title="编辑子分类"
        open={editSubModalOpen}
        onCancel={() => {
          setEditSubModalOpen(false);
          editSubForm.resetFields();
        }}
        onOk={() => editSubForm.submit()}
        okText="确定"
        cancelText="取消">
        <Form
          form={editSubForm}
          layout="vertical"
          onFinish={async (values) => {
            try {
              await updateSubCategory({
                id: editSub.id,
                name: values.name,
                categoryId: values.categoryId,
              });
              message.success("子分类修改成功");
              setEditSubModalOpen(false);
              editSubForm.resetFields();
              fetchCategories(pagination.page, pagination.size);
              fetchAllCategories(); // 刷新所有分类列表
            } catch {
              message.error("修改失败");
            }
          }}>
          <Form.Item
            name="name"
            label="子分类名称"
            rules={[{ required: true, message: "请输入子分类名称" }]}>
            <Input placeholder="请输入子分类名称" />
          </Form.Item>
          <Form.Item
            name="categoryId"
            label="父分类"
            rules={[{ required: true, message: "请选择父分类" }]}>
            <Select placeholder="请选择父分类">
              {categoryList.map((cat) => (
                <Select.Option key={cat.id} value={cat.id}>
                  {cat.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
